use postgres::{Client, Error, NoTls};

struct Nation {
    nationality: String,
    count: i64,
}

fn main() -> Result<(), Error> {
    let mut client = Client::connect(
        "postgresql://postgres:123456@localhost:5432/postgres",
        NoTls,
    )?;

    client.batch_execute(
        "\
        CREATE TABLE IF NOT EXISTS artists (
            constituent_id SERIAL PRIMARY KEY,
            display_name VARCHAR,
            artist_bio VARCHAR,
            nationality VARCHAR,
            gender VARCHAR,
            begin_date VARCHAR,
            end_date VARCHAR,
            wiki_qid VARCHAR,
            ULAN VARCHAR
        )
    ",
    )?;

    for row in client.query("SELECT nationality, COUNT(nationality) AS count FROM artists GROUP BY nationality ORDER BY count DESC", &[])? {
        let (nationality, count): (Option<String>, Option<i64>) = (row.get(0), row.get(1));

        if nationality.is_some() && count.is_some() {
            let nation = Nation {
                nationality: nationality.unwrap(),
                count: count.unwrap(),
            };
            println!("{} {}", nation.nationality, nation.count);
        }
    }

    Ok(())
}
